//index.js
const app = getApp()
const db = wx.cloud.database()
const tmpId = 'YK_vlCwV05nXgvzA26GUQjGD8I20YSwYiImiTeyIr-w'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    room: {
      typeName: '加载中'
    },
    userInfo: '',
    roomId: '',
    memberNum: 0,
    reportText: '',
    typeMap: {
      airplane: '飞机',
      train: '火车',
      car: '汽车',
      ship: '轮船',
      other: '其他',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var roomId = options.roomId
    if (!roomId) {
      console.error("missing room id", options)
      return
    }
    this.setData({
      roomId: roomId,
    })


    // wait openid ready
    var self = this
    var openId = app.globalData.openid
    if (!openId) {
      setTimeout(function() {
        self.onLoad(options)
      }, 500)
      return
    }

    // 初始化页面
    self.initRoom(roomId)


    // 检查是否有权限

    // 获取用户信息
    wx.getSetting({
      withSubscriptions: true,
      success: res => {
        console.log('res', res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接加入
          wx.getUserInfo({
            success: res => {
              this.setData({
                userInfo: res.userInfo
              })
              self.joinRoom()
            }
          })
        }
        if (!res.authSetting['scope.subscribeMessage']) {
          //开启订阅
          wx.showModal({
            content: '请同意订阅消息',
            complete: () => {
              wx.requestSubscribeMessage({
                tmplIds: [tmpId],
                success: res => {
                  console.log('scope.subscribeMessage done')
                },
                fail: console.error
              })
            }
          })
        }
      }
    })
  },

  // 加入同行者时处理
  onJoinRoom: function(e) {
    if (!e.detail.userInfo) {
      wx.showToast({
        title: '请同意获取信息',
        icon: 'none',
      })
      return
    }
    var self = this
    self.setData({
      userInfo: e.detail.userInfo
    })
    self.joinRoom()
    //开启订阅
    wx.showModal({
      content: '请同意订阅消息',
      complete: () => {
        wx.requestSubscribeMessage({
          tmplIds: [tmpId],
          success: res => {
            console.log('scope.subscribeMessage done')
          },
          fail: console.error
        })
      }
    })

    wx.requestSubscribeMessage({
      tmplIds: [tmpId],
      success: res => {
        console.log('scope.subscribeMessage done')
      },
      fail: console.error
    })
  },

  // 加入同行者
  joinRoom: function() {
    var roomId = this.data.roomId
    var openId = app.globalData.openid
    var self = this

    db.collection("member").doc(roomId + '_' + openId).set({
      data: {
        openId: openId,
        roomId: roomId,
        status: 0,
        src: self.data.userInfo.avatarUrl,
        userInfo: self.data.userInfo,
      },
      success: function(e) {
        console.log("join succ", e)
        self.onShow() // 刷新一次页面数据
      },
      fail: console.log
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  initRoom: function(roomId) {
    console.log('init room', roomId)
    var self = this
    db.collection('roomInfo').where({
      _id: roomId
    }).get({
      success: function(e) {
        console.log("room info", e.data[0])
        self.setData({
          room: {
            id: e.data[0]._id,
            typeName: e.data[0].typeName,
            typeValue: e.data[0].typeValue,
            date: e.data[0].date,
            wxacode: e.data[0].wxacode,
          }
        })
      },
      fail: function(e) {
        wx.showToast({
          title: '信息不存在',
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var roomId = this.data.roomId
    var self = this
    db.collection("member").where({
      roomId: roomId,
      status: 0
    }).count({
      success: res => {
        self.setData({
          memberNum: res.total,
        })
      },
      fail: console.error,
    })


    db.collection("report").where({
      roomId: roomId
    }).count({
      success: res => {
        if (res.total > 0) {
          self.setData({
            reportText: "共有" + res.total + "例报告",
          })
        }
      },
      fail: console.error,
    })

  },

  // 显示二维码
  showWXCode: function() {
    wx.previewImage({
      current: this.data.room.wxacode, // 当前显示图片的http链接
      urls: [this.data.room.wxacode] // 需要预览的图片http链接列表
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // 退出同行者
  exitRoom: function() {
    var self = this

    wx.showModal({
      content: '退出后将无法收到后续的订阅消息',
      success: res => {
        if (res.confirm) {
          console.log("start exit", self.data.room.id, app.globalData.openid)
          db.collection("member").where({
            roomId: self.data.room.id,
            openId: app.globalData.openid,
          }).update({
            data: {
              status: 1
            },
            success: res => {
              wx.showToast({
                title: '退出成功',
                duration: 2000,
              })

              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/focus/focus',
                })
              }, 1000)
            },
            fail: console.log,
          })
        }
      }
    })
  },
})